package com.icast.api;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;

import com.icast.interlayer.Interlayer;
import com.icast.tools.LogCat;
import com.smit.adapter.DVBAdapter;
import com.smit.adapter.DVBDevice;
import com.smit.adapter.IDVBDeviceCallback;
import com.smit.dvb.CIMenuInfo;
import com.smit.dvb.CIPinInfo;
import com.smit.dvb.DVBServiceInfo;
import com.smit.dvb.DVBTunerInfo;
import com.smit.dvb.ci.CIControl;
import com.smit.dvb.ci.ICICallback;
import com.smit.dvb.jni.DVB;
import com.smit.dvb.scan.IScanCallback;
import com.smit.dvb.scan.ScanControl;
import com.smit.dvb.service.IServiceCallback;
import com.smit.dvb.service.ServiceControl;
import com.smit.dvb.setup.SetupControl;
import com.smit.dvb.system.ISystemCallback;
import com.smit.dvb.system.SystemControl;
import com.smit.icast.ICastInitializer;

/**
 * iCast SDK 底层接口实现。本类中的方法请勿由应用直接调用，若有需要请调用ICast类中的方法。
 * 
 * @author yuchen
 */
@SuppressLint("HandlerLeak")
public class ICastApiInterface implements ISystemCallback, IDVBDeviceCallback, IScanCallback, IServiceCallback,
		ICICallback {

	/** 接口类实例 **/
	private static ICastApiInterface iCastApiInterface;
	/** 所有使用的设备单例 */
	public static DVBDevice dvbDevice;
	/** dvb控制系统单例 */
	public static SystemControl systemControl;
	/** 搜台控制系统单例 */
	public static ScanControl scanControl;
	/** 设置DVB播放单例 */
	public static SetupControl setupControl;
	/** DVB播放控制单例 */
	public static ServiceControl serviceControl;
	/** CI MMI控制单例 */
	public static CIControl ciControl;

	public ICastApiInterface(Context context) {
		iCastApiInterface = this;
		start(context);
	}

	private static void start(Context context) {
		// 初始化SDK
		ICastInitializer.getInstance().initializeICast(context, "10112016", "5067da30977b2219");
		// 初始化控制单例
		dvbDevice = DVBAdapter.getInstance().getDVBDeviceManager().getDVBDevice();
		systemControl = DVBAdapter.getInstance().getDVBManager().getSystemControl();
		scanControl = DVBAdapter.getInstance().getDVBManager().getScanControl();
		setupControl = DVBAdapter.getInstance().getDVBManager().getSetupControl();
		serviceControl = DVBAdapter.getInstance().getDVBManager().getServiceControl();
		ciControl = DVBAdapter.getInstance().getDVBManager().getCIControl();
		// 注册事件回调
		addSystemCallback();
		addDVBDeviceCallback();
		addDVBCallback();
		addCICallback();
	}

	public static void stop() {
		stopDVBService();
		// 注销事件回调
		removeSystemCallback();
		removeDVBDeviceCallback();
		removeDVBCallback();
		removeCICallback();
	}

	/**************************************** DVB系统 ****************************************/

	/**
	 * 注册DVB系统回调
	 */
	private static void addSystemCallback() {
		systemControl.addCallback(iCastApiInterface);
	}

	/**
	 * 移除DVB系统回调
	 */
	private static void removeSystemCallback() {
		systemControl.removeCallback(iCastApiInterface);
	}

	/**
	 * 唤醒DVB系统
	 */
	public static void resumeSystemControl() {
		systemControl.resume();
	}

	/**
	 * DVB系统待命
	 */
	public static void standbySystemControl() {
		systemControl.standby();
	}

	/**
	 * 判断DVB是否初始化
	 */
	public static boolean isbDVBInitOk() {
		boolean isbDVBInitOk = DVB.getInstance().isbDVBInitOk();
		return isbDVBInitOk;
	}

	/**
	 * DVB系统回调
	 */
	@Override
	public void handleSystemCallbackMsg(int i, Object o) {
		Message handlerMsg = systemHandler.obtainMessage(i, o);
		handlerMsg.sendToTarget();
	}

	private Handler systemHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SystemControl.MSG_SYSTEM_ERROR:
				LogCat.log("系统出错");
				break;
			case SystemControl.MSG_SYSTEM_INITIALIZE:
				LogCat.log("系统初始化");
				break;
			case SystemControl.MSG_SYSTEM_RESUME:
				LogCat.log("系统唤醒");
				break;
			case SystemControl.MSG_SYSTEM_STANDBY:
				LogCat.log("系统待机");
				break;
			case SystemControl.MSG_SYSTEM_TERMINATE:
				LogCat.log("系统结束");
				break;
			case SystemControl.MSG_SYSTEM_INIT_OK:
				LogCat.log("系统初始化完成");
				break;
			default:
				break;
			}
		}
	};

	/**************************************** dongle设备状态 ****************************************/

	/**
	 * 注册dongle状态回调
	 */
	private static void addDVBDeviceCallback() {
		dvbDevice.addCallback(iCastApiInterface);
	}

	/**
	 * 移除dongle状态回调
	 */
	private static void removeDVBDeviceCallback() {
		dvbDevice.removeCallback(iCastApiInterface);
	}

	/**
	 * dongle设备状态回调
	 */
	@Override
	public void handleDVBDeviceCallbackMsg(int i, Object o) {
		Message handlerMsg = dvbHandler.obtainMessage(i, o);
		handlerMsg.sendToTarget();
	}

	private Handler dvbHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DVBDevice.DVB_DEVICE_DISCONNECTED:
				LogCat.log("设备断开");
				break;
			case DVBDevice.DVB_DEVICE_CONNECTED:
				LogCat.log("设备连接上");
				break;
			case DVBDevice.DVB_DEVICE_ERROR:
				LogCat.log("设备出错");
				break;
			case DVBDevice.DVB_DEVICE_IS_RESETTING:
				LogCat.log("设备正在复位");
				break;
			case DVBDevice.DVB_DEVICE_HAS_RESET:
				LogCat.log("设备复位完成");
				break;
			case DVBDevice.DVB_DEVICE_INIT_OK:
				LogCat.log("设备初始化成功");
				break;
			case DVBDevice.DVB_DEVICE_INIT_FAIL:
				LogCat.log("设备初始化失败");
				break;
			default:
				break;
			}
		}
	};

	/**************************************** 搜台 ****************************************/

	/**
	 * 注册搜台回调
	 */
	private static void addScanCallback() {
		scanControl.addCallback(iCastApiInterface);
	}

	/**
	 * 移除搜台回调
	 */
	private static void removeScanCallback() {
		scanControl.removeCallback(iCastApiInterface);
	}

	/**
	 * 自动搜台
	 */
	public static void startAutoScan() {
		stopDVBService();
		addScanCallback();
		scanProgress = 0;
		scanCount = 0;
		scanControl.autoScan(115000, 858000);
	}

	/**
	 * 全频搜台
	 */
	public static void startFullScan() {
		stopDVBService();
		addScanCallback();
		scanProgress = 0;
		scanCount = 0;
		scanControl.fullScan(115000, 858000);
	}

	/**
	 * 手动搜台
	 */
	public static void startManualScan(DVBTunerInfo dvbTunerInfo) {
		stopDVBService();
		addScanCallback();
		scanProgress = 0;
		scanCount = 0;
		scanControl.manualScan(dvbTunerInfo);
	}

	/**
	 * 停止搜台
	 */
	public static void AbortScan() {
		scanProgress = 0;
		scanControl.abortScan();
	}

	private static int scanProgress;
	private static int scanCount;

	/**
	 * 获取搜台进度
	 */
	private int getScanProgress(Object o) {
		int progress = Integer.parseInt(o.toString());
		return progress;
	}

	/**
	 * 获取搜到节目的个数
	 */
	private int getScanServices(Object o) {
		DVBServiceInfo[] servicesList = (DVBServiceInfo[]) o;
		return servicesList.length;
	}

	/**
	 * 搜台回调
	 */
	@Override
	public void handleScanCallbackMsg(int i, Object o) {
		Message handlerMsg = scanHandler.obtainMessage(i, o);
		handlerMsg.sendToTarget();
	}

	private Handler scanHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ScanControl.MSG_SCAN_ERROR:
				LogCat.log("搜台出错");
				break;
			case ScanControl.MSG_SCAN_START:
				LogCat.log("搜台开始");
				break;
			case ScanControl.MSG_SCAN_DVB_NETWORK:
				LogCat.log("扫描运营商");
				break;
			case ScanControl.MSG_SCAN_TUNER_LOCKED:
				// LogCat.d("锁台");
				break;
			case ScanControl.MSG_SCAN_PROGRESS_CHANGED:
				if (getScanProgress(msg.obj) > scanProgress) {
					scanProgress = getScanProgress(msg.obj);
					LogCat.log("搜台进度改变" + scanProgress);
				}
				break;
			case ScanControl.MSG_SCAN_SERVICES_FOUND:
				int services = getScanServices(msg.obj);
				scanCount += services;
				LogCat.log("搜到节目" + services + "个，总台数" + scanCount);
				break;
			case ScanControl.MSG_SCAN_FINISH:
				LogCat.log("搜台结束");
				removeScanCallback();
				Interlayer.onScanOver();
				break;
			default:
				break;
			}
		}
	};

	/**************************************** CI MMI ****************************************/

	/**
	 * 注册CI回调
	 */
	private static void addCICallback() {
		ciControl.addCallback(iCastApiInterface);
	}

	/**
	 * 移除CI回调
	 */
	private static void removeCICallback() {
		ciControl.removeCallback(iCastApiInterface);
	}

	/**
	 * 打开CI MMI Menu
	 */
	public static void openSession() {
		ciControl.openSession();
	}

	/**
	 * 关闭CI MMI Menu
	 */
	public static void closeSession() {
		ciControl.closeSession();
	}

	/**
	 * 获取CI MMI Menu相关信息
	 */
	public static CIMenuInfo getCIMenuInfo() {
		CIMenuInfo ciMenuInfo = ciControl.getCIMenuInfo();
		return ciMenuInfo;
	}

	/**
	 * 进入 CI MMI Menu中list的某个item, 0为返回上一级
	 */
	public static void selectCIMenuItem(int id) {
		ciControl.selectMenuItem(id);
	}

	/**
	 * 获取CI MMI Pin相关信息
	 */
	public static CIPinInfo getCIPinInfo() {
		CIPinInfo ciPinInfo = ciControl.getCIPinInfo();
		return ciPinInfo;
	}

	/**
	 * 给CI MMI Pin返回Pin码
	 */
	public static void setCIPinInfo(String pinText) {
		LogCat.log("setCIPinInfo = " + pinText);
		ciControl.setPin(pinText);
	}

	/**
	 * CI回调
	 */
	@Override
	public void handleCICallbackMsg(int i, Object o) {
		Message handlerMsg = CIHandler.obtainMessage(i, o);
		handlerMsg.sendToTarget();
	}

	private Handler CIHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case CIControl.MSG_CI_DATA_UPDATED:
				// 包括智能卡信息、硬件信息、设备ID、设备类型
				LogCat.log("刷新CI数据");
				break;
			case CIControl.MSG_CI_SHOW_MMI_MENU:
				LogCat.log("显示CI MMI Menu");
				Interlayer.showCiDialog();
				break;
			case CIControl.MSG_CI_UPDATE_MMI_MENU:
				LogCat.log("刷新CI MMI Menu");
				Interlayer.showCiDialog();
				break;
			case CIControl.MSG_CI_HIDE_MMI_MENU:
				LogCat.log("关闭CI MMI Menu");
				Interlayer.closeCiDialog();
				break;
			case CIControl.MSG_CI_SHOW_PIN_DIALOG:
				LogCat.log("显示CI MMI Pin");
				Interlayer.showPinDialog();
				break;
			case CIControl.MSG_CI_HIDE_PIN_DIALOG:
				LogCat.log("关闭CI MMI Pin");
				Interlayer.closePinDialog();
				break;
			default:
				break;
			}
		}
	};

	/**************************************** DVB播放 ****************************************/

	/**
	 * 注册DVB播放回调
	 */
	private static void addDVBCallback() {
		serviceControl.addCallback(iCastApiInterface);
	}

	/**
	 * 移除DVB播放回调
	 */
	private static void removeDVBCallback() {
		serviceControl.removeCallback(iCastApiInterface);
	}

	/**
	 * 停止DVB播放服务
	 */
	private static void stopDVBService() {
		if (serviceControl != null) {
			serviceControl.stopDVBService();
		}
	}

	/**
	 * 获取所有搜索到的节目
	 */
	public static DVBServiceInfo[] getDVBServiceInfos() {
		return serviceControl == null ? null : serviceControl.getAllServices();
	}

	/**
	 * 播放指定DVB节目
	 * 
	 * @param index
	 *            要播放的频道序号，从0开始
	 */
	public static void startDVBPlayer(int index) {
		LogCat.log("启动播放：" + (index + 1) + "台");
		setupControl.setServiceGroupId(DVBServiceInfo.DVB_GROUP_TV);// 第一次播放之前需要设置播放组
		serviceControl.playServiceByIndex(index);
	}

	/**
	 * 停止DVB播放
	 */
	public static void stopDVBPlayer() {
		stopDVBService();
		Interlayer.stopPlayer();
	}

	/**
	 * DVB系统回调
	 */
	@Override
	public void handleServiceCallbackMsg(int i, Object o) {
		Message handlerMsg = DVBHandler.obtainMessage(i, o);
		handlerMsg.sendToTarget();
	}

	private Handler DVBHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case ServiceControl.MSG_SERVICE_HAS_TS:
				LogCat.log("有TS流");
				break;
			case ServiceControl.MSG_SERVICE_FREE_AND_RESET_PLAYER:
				LogCat.log("清流且复位player");
				Interlayer.startPlayer();
				break;
			case ServiceControl.MSG_SERVICE_FREE_WITHOUT_RESET_PLAYER:
				LogCat.log("清流且不复位player");
				break;
			case ServiceControl.MSG_SERVICE_SCRAMBLED:
				LogCat.log("加密节目");
				break;
			case ServiceControl.MSG_SERVICE_TS_PLAYER_PREPARED:
				LogCat.log("准备player");
				break;
			case ServiceControl.MSG_SERVICE_SIGNAL_BAD:
				LogCat.log("无信号或信号弱");
				break;
			case ServiceControl.MSG_SERVICE_SIGNAL_GOOD:
				LogCat.log("信号好");
				Interlayer.startPlayer();
				break;
			case ServiceControl.MSG_SERVICE_STOPPED:
				LogCat.log("停止player");
				Interlayer.stopPlayer();
				break;
			default:
				break;
			}
		}
	};
}